package com.jwaoo.chat.session.snap;

import android.content.Context;

import com.dx.as.common.file.AttachmentStore;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.data.db.MessageHandler;

/**
 * Created by jwaoo on 2017/8/9.
 */

public class AutoDescThread extends Thread{
    private int number;
    private AutoDescCallback callback;
    private Context context;
    private Message message;
    public AutoDescThread(Context context,Message message){
        this(context,message,null);
    }

    public AutoDescThread(Context context, Message message, AutoDescCallback callback){
        this.message = message;
        this.number = message.getTime();
        this.callback = callback;
        this.context = context;
        MessageHandler.getInstace(context).handlerMessages(MessageHandler.UPDATE_MESSAGE,message);
    }

    public void setCallback(AutoDescCallback callback) {
        this.callback = callback;
    }

    public void run() {
        try{
            while(number > 0){
                number --;
                if (callback != null)
                    callback.updateTime(number,this);
                Thread.sleep(1000);
                if (number == 0) {
                    deleteMessage();
                    AutoDescManager.removeTask(message.getMsgid());
                    this.destroy();
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public interface AutoDescCallback{
        void updateTime(int number,AutoDescThread task);
    }

    public void deleteMessage(){
        if (message == null ) return;
        MessageHandler.getInstace(context).handlerMessages(MessageHandler.DELETE_MESSAGE,message);
        FileAttachment attachment = message.getAttachment();
        if (attachment == null) return;
        AttachmentStore.delete(attachment.getPath());
        AttachmentStore.delete(attachment.getThumbPath());
    }

}
